<template>
  <div class="flex flex-col flex-1 overflow-auto domain-table-list">
    <filter-bar
      :loading="loading"
      :is-select="!!selectedRows?.length"
      @create="toAddDomainPage"
      @batch="openBatchDialog"
      @search="handleSearch"
      @refresh="getList()"
      @join-group="openJoinGroupDialog()"
    ></filter-bar>

    <div class="flex-1 overflow-auto table-wrap">
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="tableData"
        height="100%"
        class="basic-table"
        :tooltip-options="{ popperClass: 'basic-tooltip' }"
        @sort-change="handleSortChange"
        @selection-change="handleTableSelectionChange"
      >
        <template #empty><TableEmpty /></template>
        <el-table-column
          type="selection"
          fixed="left"
          width="50px"
        ></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          width="80px"
        ></el-table-column>
        <el-table-column label="域名" show-overflow-tooltip min-width="150">
          <template #default="{ row }">
            <span v-format-table-cell="row.name"></span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="!hideColumns?.includes('user')"
          label="所属用户"
          prop="user"
          min-width="120"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span v-format-table-cell="row.username"></span>
          </template>
        </el-table-column>
        <el-table-column label="分组" min-width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="user" v-format-table-cell="row.group_name"></span>
            <span v-else v-format-table-cell="row.admin_group_name"></span>
          </template>
        </el-table-column>
        <el-table-column label="记录数" min-width="100">
          <template #default="{ row }">
            <span v-format-table-cell="row.rr_num"></span>
          </template>
        </el-table-column>
        <!-- <el-table-column
          sortable="custom"
          prop="created_at"
          label="添加时间"
          min-width="180"
        >
          <template #default="{ row }">
            <span v-format-unix="row.created_at"></span>
          </template>
        </el-table-column> -->

        <!-- <el-table-column label="DNS服务器地址" min-width="220">
          <template #default="{ row }">
            <div class="flex items-center justify-between">
              <div class="table-dns-wrapper">
                <div
                  v-for="(item, index) in row.assign_ns_list"
                  :key="index"
                  class="dns"
                >
                  <TextEll :offset="2" :content="emptyText(item?.addr)" />
                </div>
              </div>
              <el-icon
                class="cursor-pointer"
                color="#164CFF"
                size="16"
                @click="openEditDnsDialog(row)"
              >
                <Edit />
              </el-icon>
            </div>
          </template>
        </el-table-column> -->
        <el-table-column label="NS服务器状态" min-width="140">
          <template #default="{ row }">
            <div class="flex items-center">
              <dns-status :status="row.ns_status">
                <template #tooltip>
                  <div class="leading-[12px]">
                    <div class="pb-2">请到域名注册商处修改DNS服务器为：</div>
                    <div class="flex items-center justify-between gap-x-1">
                      <div class="break-all">
                        <div class="pb-3">
                          {{ row.assign_ns_list[0].addr }}
                        </div>
                        <div class="pb-1">
                          {{ row.assign_ns_list[1].addr }}
                        </div>
                      </div>
                      <el-link
                        class="text-blue-400 whitespace-nowrap"
                        :underline="false"
                        @click="openEditDnsDialog(row)"
                      >
                        修改
                      </el-link>
                    </div>
                  </div>
                </template>
              </dns-status>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="220">
          <template #default="{ row }">
            <basic-edit-table-remark
              :content="row.remark"
              :submit="value => handleEditRemark(row, value)"
            />
          </template>
        </el-table-column>
        <el-table-column
          sortable="custom"
          prop="updated_at"
          label="更新时间"
          min-width="180"
        >
          <template #default="{ row }">
            <span v-format-unix="row.updated_at"></span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140" fixed="right">
          <template #default="{ row }">
            <div class="flex gap-x-4">
              <el-link
                type="primary"
                :underline="false"
                @click="toParseSetting(row)"
              >
                解析设置
              </el-link>
              <el-link
                type="danger"
                :underline="false"
                @click="handleDelete(row)"
              >
                删除
              </el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="py-4 pl-[24px]">
      <basic-pagination
        ref="paginationRef"
        :table-ref="tableRef"
        :batch-button-props="{
          disabled: !selectedRows || selectedRows.length === 0
        }"
        :pagination="pagination"
        @change="getList"
      ></basic-pagination>
    </div>
  </div>

  <edit-dns-dialog
    v-model:visible="editDns.visible"
    v-model:loading="editDns.loading"
    v-model:record="editDns.record"
    :save-method="handleEditDnsServer"
    @reload="getList"
  ></edit-dns-dialog>

  <join-group-dialog
    v-model:visible="joinGroup.visible"
    v-model:loading="joinGroup.loading"
    @reload="getList"
  ></join-group-dialog>

  <batch-operation
    v-model:visible="batchDialogVisible"
    :user="user"
    @refresh="handleSearch()"
  ></batch-operation>
</template>

<script setup lang="ts">
/**
 * 此组件需要根据 props 的 user 来决定操作的是所有域名，还是用户域名
 */
import type { TableInstance } from 'element-plus'

import type { UserModel } from '@/apis/model/user'
import { useListRequest } from '@/hooks/useListRequest'
import useTableSelection from '@/hooks/useTableSelection'
import BatchOperation from '@/views/modules/user/domain/batch/BatchOperation.vue'

import FilterBar from './FilterBar.vue'
import useDomainActions from './hooks/useDomainActions'
import useDomainDialog from './hooks/useDomainDialog'
import type { IQuery } from './types'

interface IProps {
  hideColumns?: string[]
  user?: UserModel
}

const props = defineProps<IProps>()

const route = useRoute()
const router = useRouter()
const tableRef = ref<TableInstance>()
const paginationRef = ref()

const batchDialogVisible = ref(false)

const openBatchDialog = () => {
  batchDialogVisible.value = true
  history.state.domains = (selectedRows.value ?? []).map(v => v.name!)
}

/**
 * 查询参数
 */
const queryParams = reactive<IQuery>({
  user_id: props.user?.id,
  group_id: '',
  admin_group_id: '',
  name: '',
  remark: '',
  sort: '',
  order: ''
})

/**
 * 获取列表数据
 */
const {
  data: tableData,
  getList,
  pagination,
  loading
} = useListRequest(domainListApi, queryParams)

function handleSortChange(params: SortParams) {
  const { sort, order } = getSortValue(params)
  queryParams.sort = sort!
  queryParams.order = order!
  pagination.page = 1
  getList()
}

/**
 * 搜索
 */
const handleSearch = () => {
  pagination.page = 1
  getList()
}

/**
 * 列表选中
 */
const { selectedRows, handleTableSelectionChange } = useTableSelection(
  tableData,
  paginationRef
)

const toAddDomainPage = () => {
  router.push({
    name: 'UserDomainAdd',
    params: {
      userId: props.user?.id!
    },
    state: {
      domains: (selectedRows.value ?? []).map(v => v.name!)
    }
  })
}

/**
 * dialog相关状态及方法
 */
const { editDns, openEditDnsDialog, joinGroup, openJoinGroupDialog } =
  useDomainDialog()

/**
 * 域名相关操作
 */
const { handleDelete, handleEditDnsServer, toParseSetting, handleEditRemark } =
  useDomainActions(getList)

onBeforeMount(() => {
  const groupId = (route.query.groupId as string) || ''
  if (props.user?.id) {
    queryParams.group_id = groupId
  } else {
    queryParams.admin_group_id = groupId
  }
})

/**
 * 依赖注入
 */
provide('queryParams', queryParams)
provide('selectedRows', selectedRows)

provide('user', toRef(props, 'user'))
</script>

<style scoped lang="scss"></style>
